package com.multysite.controller.admin;

import java.io.IOException;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.NamespaceManager;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.multysite.entity.admin.Application;
import com.multysite.entity.admin.ApplicationConfig;
import com.multysite.entity.admin.ApplicationTemplate;
import com.multysite.model.admin.ApplicationConfigModel;
import com.multysite.model.admin.ApplicationModel;
import com.multysite.model.admin.ApplicationTemplateModel;
import com.multysite.util.IdUniqueHelper;
import com.multysite.util.Setting;
import com.multysite.util.Utils;

@SuppressWarnings("serial")
public class NewApplicationServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(NewApplicationServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			resp.setCharacterEncoding("utf-8");
			if (NamespaceManager.get().equals(Setting.getGeneralNamespace())) {
				Application obj = new Application();
				req.setAttribute("site", obj);
				req.getRequestDispatcher("/admin/pages/create.jsp").forward(
						req, resp);
			} else {
				int port = req.getServerPort();
				NamespaceManager.set(Setting.getGeneralNamespace());
				resp.sendRedirect("http://" + Setting.getDomain() + ":" + port
						+ "/create");
			}
		} catch (ServletException e) {
			e.printStackTrace();
			log.warning(e.toString());
			resp.sendError(4000,
					"Website is down for maintenance. We are sorry for the inconvenience !");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			TreeMap<String, String> error = new TreeMap<String, String>();
			String applicationId = req.getParameter("applicationId");
			String applicationTitle = req.getParameter("applicationTitle");
			Application obj = new Application();
			if (applicationId != null && applicationId.length() > 2) {
				/*
				 * Check exits application id
				 */
				Application checkObj = ApplicationModel.getById(applicationId);
				if (checkObj != null) {
					error.put(
							"applicationId",
							applicationId
									+ " is not avaiable. Please try another application id ");
				} else {
					obj.setId(applicationId);
				}
			} else {
				error.put("applicationId",
						"Application Id must be more than 2 character.");
			}
			if (applicationTitle != null && applicationTitle.length() > 0) {
				obj.setTitle(applicationTitle);
			} else {
				error.put("applicationTitle",
						"Application Title cannot be empty.");
			}

			if (error.size() > 0) {
				req.setAttribute("error", error);
				req.setAttribute("site", obj);
				req.getRequestDispatcher("/admin/pages/create.jsp").forward(
						req, resp);
			} else {
				/*
				 * Add site to default Namespace
				 */
				UserService userService = UserServiceFactory.getUserService();
				User user = userService.getCurrentUser();
				obj.setUserEmail(user.getEmail());
				ApplicationModel.insert(obj);

				/*
				 * Add relate site object to detail Namespace (incluse site
				 * config and site template)
				 */
				String ns = obj.getId();
				/*
				 * site template, add default template
				 */
				ApplicationTemplate template = new ApplicationTemplate();
				template.setId(IdUniqueHelper.getId());
				template.setHome(Utils.getContentPhp(
						"/templates/classic/home.php", getServletContext()));
				template.setCategory(Utils.getContentPhp(
						"/templates/classic/category.php", getServletContext()));
				template.setDetail(Utils.getContentPhp(
						"/templates/classic/detail.php", getServletContext()));
				template.setTag(Utils.getContentPhp(
						"/templates/classic/tag.php", getServletContext()));
				template.setSearch(Utils.getContentPhp(
						"/templates/classic/search.php", getServletContext()));
				template.setCss(Utils
						.getContentPhp("/templates/classic/css/style.css",
								getServletContext()));
				template.setJs(Utils.getContentPhp(
						"/templates/classic/js/multysite.js",
						getServletContext()));
				ApplicationTemplateModel.insert(ns, template);

				/*
				 * site config
				 */
				ApplicationConfig config = new ApplicationConfig();
				config.setApplicationId(obj.getId());
				config.setTitle(obj.getTitle() + " Title");
				config.setDescription(obj.getTitle() + " Description");
				config.setKeyword(obj.getId());
				config.setTemplateId(template.getId());
				config.setStatus(1);
				ApplicationConfigModel.insert(ns, config);

				resp.setContentType("text/html");
				resp.getWriter().println(
						"Visit site with url : <a href=\"http://" + obj.getId()
								+ "." + req.getServerName() + "\">"
								+ obj.getId() + "." + req.getServerName()
								+ "</a><br>");
				resp.getWriter()
						.println(
								"<a href=\"http://"
										+ obj.getId()
										+ "."
										+ req.getServerName()
										+ "/admin\">Setup</a> your application OR <a href=\"http://"
										+ obj.getId() + "."
										+ req.getServerName()
										+ "/admin/news/add\">Add news</a>");
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
			log.warning(e.toString());
			resp.sendError(4000,
					"Website is down for maintenance. We are sorry for the inconvenience !");
		}
	}
}
